import { Button, Form, Input, Popconfirm, Radio, Space, Switch } from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";

import CommonPage from "@/components/page/CommonPage";
import styled from "styled-components";
import Add from "@/components/svg/action-slot-icon/Add";
import CrudTable from "@/components/table/CrudTable";
import QueryBarItem from "@/components/query-bar/QueryBarItem";
import { Icon } from "@iconify/react";
import { formatDate } from "@/utils/common/common";
import { useEffect, useRef, useState } from "react";
import useGetState from "@/hooks/useGetState";
import { deleteMenu, getMenus, saveOrUpdateMenu } from "@/api/menu";
import useMyContext from "@/hooks/useContext";
import CrudModal from "@/components/table/CrudModal";
import useCRUD from "@/hooks/useCRUD";
import IconPicker from "@/components/icon/IconPicker";
import InputNumber from "@/components/common/InputNumber";

const Styled = styled.div``;

const Menu = () => {
  //所有switch的状态loading管理
  const [loadingStates, setLoadingStates] = useState({});
  const { messageApi } = useMyContext();

  const $table = useRef();
  //搜索框参数
  const [queryItems, setQueryItems, getQueryItems] = useGetState({});
  //是否展示菜单类型
  const [showMenuType, setShowMenuType] = useState(false);
  // 初始化表单内容
  const [initForm, setInitForm] = useState({
    order_num: 1,
    is_hidden: 0,
    is_catalogue: true, // 默认选中"目录"
    component: "Layout", // 目录必须是 "Layout", 一级菜单可以是 "Layout"
    parent_id: 0, // 目录和一级菜单的父id是 0
  });
  const columns = [
    {
      title: "菜单名称",
      key: "name",
      width: 80,
      ellipsis: { showTitle: true },
      render(_, record, index) {
        return <>{record.name}</>;
      },
    },
    {
      title: "图标",
      key: "icon",
      width: 30,
      align: "center",
      render(_, record, index) {
        return <Icon icon={record.icon} size={20} />;
      },
    },
    {
      title: "排序",
      key: "order_num",
      width: 30,
      ellipsis: { showTitle: true },
      align: "center",
      render(_, record, index) {
        return record.order_num;
      },
    },
    {
      title: "访问路径",
      key: "path",
      width: 60,
      ellipsis: { showTitle: true },
      align: "center",
      render(_, record, index) {
        return record.path;
      },
    },
    {
      title: "跳转路径",
      key: "redirect",
      width: 80,
      ellipsis: { showTitle: true },
      align: "center",
      render(_, record, index) {
        return record.redirect ?? "";
      },
    },
    {
      title: "组件路径",
      key: "component",
      width: 40,
      ellipsis: { showTitle: true },
      align: "center",
      render(_, record, index) {
        //这里需要注意，项目的Layout组件使用的名字是LayoutIndex
        return record.component;
      },
    },
    {
      title: "保活",
      key: "keep_alive",
      width: 30,
      render(_, record) {
        return <span>{record.keep_alive ? "true" : "false"}</span>;
      },
    },
    {
      title: "隐藏",
      key: "is_hidden",
      width: 30,
      render(_, record) {
        return (
          <Switch
            checked={record.is_hidden}
            size="small"
            loading={!!loadingStates[record.id]}
            onClick={(bol) => {
              handleUpdateHidden(record);
            }}
          />
        );
      },
    },
    {
      title: "创建日期",
      key: "created_at",
      width: 70,
      align: "center",
      render(_, record) {
        return <span>{formatDate(record.created_at)}</span>;
      },
    },
    {
      title: "操作",
      key: "actions",
      width: 115,
      align: "center",
      render(_, record) {
        return (
          <>
            <Button
              type="link"
              style={{ marginRight: "5px", color: "green" }}
              icon={<PlusOutlined />}
              onClick={() => {
                setShowMenuType(false);
                handleEdit(record);
              }}
            >
              编辑
            </Button>
            <Button
              type="link"
              style={{ marginRight: "5px" }}
              icon={<EditOutlined />}
              onClick={() => {
                setInitForm({
                  ...initForm,
                  is_catalogue: false, // 设置非目录(显示组件路径)
                  component: "", // 手动清空组件路径
                  parent_id: record.id, // 设置父菜单id
                });
                setShowMenuType(false);
                handleAdd();
              }}
            >
              新增
            </Button>
            <Popconfirm
              title="确认删除该标签吗"
              description="删除后可在回收站中查看"
              onConfirm={() => {
                handleDelete([record.id]);
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="link"
                icon={<DeleteOutlined />}
                style={{ color: "#D03050FF" }}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  const {
    modalVisible,
    setModalVisible,
    modalTitle,
    modalLoading,
    handleAdd,
    handleDelete,
    handleEdit,
    handleSave,
    modalForm,
    setModalForm,
    modalFormRef,
    clearFormFields,
  } = useCRUD({
    name: "菜单",
    initForm,
    doCreate: saveOrUpdateMenu,
    doDelete: deleteMenu,
    doUpdate: saveOrUpdateMenu,
    refresh: () => $table.current.handleSearch(),
  });

  function updateQueryItems(newQueryItems) {
    setQueryItems(newQueryItems);
  }

  // 修改是否隐藏
  async function handleUpdateHidden(row) {
    if (!row.id) {
      messageApi.error("操作错误，请稍后重试");
      return;
    }
    try {
      setLoadingStates({ ...loadingStates, [row.id]: true });
      row.is_hidden = +row.is_hidden === 0 ? 1 : 0;
      await saveOrUpdateMenu(row);
      setLoadingStates({ ...loadingStates, [row.id]: false });
      messageApi.success(row.is_hidden ? "已隐藏" : "取消隐藏");
    } catch (error) {
      messageApi.error("设置菜单隐藏失败~");
    }
  }

  //新增菜单
  function handleClickAdd() {
    setShowMenuType(true); //显示菜单类型选择

    // 进行增加
    handleAdd();
  }

  function updateModalForm(val) {
    setModalForm({
      ...modalForm,
      ...val,
    });
  }

  useEffect(() => {
    $table.current.handleSearch();
  }, []);

  return (
    <Styled>
      <CommonPage title="菜单管理">
        <div className="action-slot" slot="action">
          <Button type="primary" icon={<Add />} onClick={handleClickAdd}>
            新建菜单
          </Button>
        </div>

        <CrudTable
          ref={$table}
          columns={columns}
          queryItems={queryItems}
          updateQueryItems={updateQueryItems}
          getQueryItems={getQueryItems}
          singleLine={true}
          getData={getMenus}
          hasRowSelection={false}
        >
          <div className="queryBar-slot flex label-ml-15" slot="queryBar">
            <QueryBarItem label="菜单名" labelWidth={50}>
              <Input
                placeholder="请输入菜单名"
                allowClear
                value={queryItems.keyword}
                onChange={(e) => {
                  setQueryItems({
                    ...queryItems,
                    keyword: e.target.value,
                  });
                }}
              />
            </QueryBarItem>
          </div>
        </CrudTable>

        {/* 新增，修改，查看 */}
        <CrudModal
          visible={modalVisible}
          setModalVisible={setModalVisible}
          loading={modalLoading}
          title={modalTitle}
          handleSave={handleSave}
          clearFormFields={clearFormFields}
        >
          <Form
            form={modalFormRef}
            name="menu"
            labelAlign="left"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={{
              ...initForm,
            }}
          >
            {showMenuType ? (
              <Form.Item label="菜单类型" name="type">
                <Radio.Group
                  value={modalForm.is_catalogue}
                  name="radiogroup"
                  onChange={(e) => {
                    setModalForm({
                      ...modalForm,
                      is_catalogue: e.target.value,
                    });
                  }}
                >
                  <Space size="large">
                    <Radio value={true}>目录</Radio>
                    <Radio value={false}>一级菜单</Radio>
                  </Space>
                </Radio.Group>
              </Form.Item>
            ) : null}
            {/* 可以不给modalForm中绑定数据，因为获取数据是通过表单引用获取的 */}
            <Form.Item label="菜单名称" name="name">
              <Input
                placeholder="请输入菜单名称"
                onChange={(e) => {
                  setModalForm({
                    ...modalForm,
                    name: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item label="菜单图标" name="icon">
              <IconPicker
                value={modalForm.icon}
                updateModalForm={updateModalForm}
              ></IconPicker>
            </Form.Item>
            {!modalForm.is_catalogue ? (
              <Form.Item label="组件路径" name="component">
                <Input
                  placeholder="请输入组件路径"
                  value={modalForm.component}
                  onChange={(e) => {
                    updateModalForm({ component: e.target.value });
                  }}
                />
              </Form.Item>
            ) : null}
            <Form.Item label="访问路径" name="path">
              <Input
                placeholder="请输入访问路径"
                value={modalForm.path}
                onChange={(e) => {
                  updateModalForm({ path: e.target.value });
                }}
              />
            </Form.Item>
            <Form.Item label="跳转路径" name="redirect">
              <Input
                placeholder="只有一级菜单可以设置跳转路径"
                value={modalForm.redirect}
                onChange={(e) => {
                  updateModalForm({ redirect: e.target.value });
                }}
                disabled={modalForm.parent_id !== 0}
              />
            </Form.Item>
            <Form.Item label="显示排序" name="order_num">
              <InputNumber
                value={modalForm.order_num}
                updateModalForm={updateModalForm}
              />
            </Form.Item>
            <Form.Item label="是否隐藏" name="is_hidden">
              <Switch
                checked={modalForm.is_hidden}
                onChange={(checked) => {
                  if (checked) {
                    updateModalForm({ is_hidden: 1 });
                  } else {
                    updateModalForm({ is_hidden: 0 });
                  }
                }}
              />
            </Form.Item>
            <Form.Item label="KeepLive" name="keep_alive">
              <Switch
                checked={modalForm.keep_alive}
                onChange={(checked) => {
                  if (checked) {
                    updateModalForm({ keep_alive: 1 });
                  } else {
                    updateModalForm({ keep_alive: 0 });
                  }
                }}
              />
            </Form.Item>
          </Form>
        </CrudModal>
      </CommonPage>
    </Styled>
  );
};

export default Menu;
